package com.bluesmart.mia;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sys.DemoApp;
import com.util.Constant;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;

import android.os.Bundle;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class NotificationActivity extends BaseActivity implements OnClickListener {
	MyAdapter mAdapter;
	JSONArray mArray = new JSONArray();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_notification);
		
		((DemoApp)getApplicationContext()).isNewMsg = false;

		((TextView) findViewById(R.id.center)).setText(getString(R.string.notification));
		((Button) findViewById(R.id.right)).setCompoundDrawablesWithIntrinsicBounds(0, 0,
				R.drawable.a01, 0);
		
		ListView listview = (ListView)findViewById(R.id.listview);
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		listview.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				JSONObject item = mArray.getJSONObject(arg2);
				if(item.getInteger("type") == 2)
				{
					showQueryList(arg2);
				}
				if(item.getInteger("status") != 1) setMsgRead(item.getString("dataid"));
			}
		});
		
		sendGetHttpRequest();
		
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);
		findViewById(R.id.mind_on).setOnClickListener(this);
		findViewById(R.id.system_on).setOnClickListener(this);
	}

	class MyAdapter extends BaseAdapter {
		public int getCount() {
			if(mArray == null) return 0;
			return mArray.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_notify, null);
				foodHold.img = (ImageView) convertView.findViewById(R.id.img);
				foodHold.title = (TextView) convertView.findViewById(R.id.msg);

				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}

			JSONObject item = mArray.getJSONObject(position);
			if(item.getInteger("status") == 1) foodHold.img.setVisibility(View.INVISIBLE);
			else foodHold.img.setVisibility(View.VISIBLE);
			foodHold.title.setText(item.getString("time") + " " + item.getString("title"));
			
			foodHold.img.setTag(String.valueOf(position));
			return convertView;
		}
	}

	public final class FoodHolder {
		public ImageView img;
		public TextView title;
	}
	
	private void sendHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				mArray = JSON.parseArray(response);
				mAdapter.notifyDataSetChanged();
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/Notifications.ashx", JSON.toJSONString(params), loginHandler);
	}

	@Override
	public void onClick(View arg0) {
		switch(arg0.getId())
		{
		case R.id.left:
			finish();
			break;
			
		case R.id.right:
			sendSetHttpRequest();
			break;
			
		case R.id.mind_on:
		case R.id.system_on:
			((Button)arg0).setSelected(!((Button)arg0).isSelected());
			break;
		}
	}
	
	JSONObject mJson = null;
	private void sendGetHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				mJson = JSON.parseObject(response);
				if(mJson!= null)
				{
					if(mJson.getString("scheduleisRemind").equals("true"))
						((Button)findViewById(R.id.mind_on)).setSelected(true);
					if(mJson.getString("isSystemRemind").equals("true"))
						((Button)findViewById(R.id.system_on)).setSelected(true);
					((TextView)findViewById(R.id.min)).setText(mJson.getString("interval"));
				}
				sendHttpRequest();
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("handType", "get");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/GetMiaConfig.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	private void sendSetHttpRequest() {
		if(mJson == null)
		{
			ToastUtil.showToastWithAlertPic(R.string.error_3000);
			return;
		}
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {

				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					ToastUtil.showToastWithAlertPic(R.string.success);
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else 
				{
				}
			}
		};
		
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		if(((Button)findViewById(R.id.mind_on)).isSelected()) params.put("scheduleisRemind", true);
		else params.put("scheduleisRemind", false);
		if(((Button)findViewById(R.id.system_on)).isSelected()) params.put("isSystemRemind", true);
		else params.put("isSystemRemind", false);
		params.put("handType", "update");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/GetMiaConfig.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	void showQueryList(final int index)
	{
		String title = mArray.getJSONObject(index).getString("title");
		int pos = title.indexOf(" ");
		String email = title.substring(0, pos);
		
		new AlertDialog.Builder(this).setTitle(email + getString(R.string.apply_family)).setItems(
				new String[] { getString(R.string.agree), getString(R.string.not_agree),getString(R.string.cancel) }, 
				new DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						arg0.dismiss();
						
						if(arg1 == 0)
						{
							sendTackleHttpRequest(mArray.getJSONObject(index),true);
						}
						else if(arg1 == 1)
						{
							sendTackleHttpRequest(mArray.getJSONObject(index),false);
						}
					}
				}).show();
	}
	
	private void sendTackleHttpRequest(JSONObject item,boolean result) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					ToastUtil.showToastWithAlertPic(R.string.success);
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else 
				{
				}
			}
		};
		
		String title = item.getString("title");
		int pos = title.indexOf(" ");
		String email = title.substring(0, pos);
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("applyUser", email);
		params.put("handType", "choice");
		params.put("isAgree",result);
		params.put("isApply", "true");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/ApplyToOtherUser.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	private void setMsgRead(String dataid) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, false, false) {
			@Override
			public void onSuccess(String response) {
				if (response.contains("1000")) {
					sendHttpRequest();
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("handType", "update");
		params.put("dataid",dataid);

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/Notifications.ashx", JSON.toJSONString(params), loginHandler);
	}
}
